package logic

import (
	"app-video/common/constant"
	"app-video/common/xerr"
	"app-video/models"
	"context"
	"fmt"
	"time"

	"app-video/protos"
	"app-video/rpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type LikeVideoLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLikeVideoLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LikeVideoLogic {
	return &LikeVideoLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// LikeVideo 喜欢视频
func (l *LikeVideoLogic) LikeVideo(in *protos.FavVideoRequest) (*protos.Empty, error) {
	nowTime := time.Now().Unix()
	result, err := l.svcCtx.FavVideoModel.Insert(l.ctx, &models.Favorite{
		UserId:     in.UserId,
		VideoId:    in.VideoId,
		CreateTime: nowTime,
		UpdateTime: nowTime,
	})
	if err != nil {
		return nil, xerr.New(xerr.VideoLikeError)
	}

	videoID, err := result.LastInsertId()
	if err != nil {
		return nil, xerr.New(xerr.VideoLikeError)
	}

	favVideoKey := fmt.Sprintf("%s:%d", constant.FavVideoKey, videoID)
	_, _ = l.svcCtx.Redis.IncrbyCtx(l.ctx, favVideoKey, 1)

	userFavVideoKey := fmt.Sprintf("%s:%d", constant.UserFavVideoKey, in.UserId)
	_, _ = l.svcCtx.Redis.LpushCtx(l.ctx, userFavVideoKey, videoID)
	return &protos.Empty{}, nil
}
